# 寻找所得到的sfcWind相同的点，在符合地理选址的300多万点中确定在同一0.703*0.701的格内的点，并得到相关的经纬度
import xarray as xr
import numpy as np
import pandas as pd
import csv
from collections import defaultdict, Counter

ds = xr.open_dataset(
    "D:\\pycharm\\energy\\cmip_2020\\sfcWind_E3hr_EC-Earth3_ssp245_r1i1p1f1_gr_202001010130-202012312230.nc")

csv_counter = 1  # 用于追踪CSV文件的计数器
dic = {}
with open(r"D:\sfcWind\all1.csv", 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    next(reader)  # Skip the header row
    i = 0
    for row in reader:
        if row[2] != ' ':
            lon = float(row[0])  # Assuming the latitude is in the first column
            lat = float(row[1])  # Assuming the longitude is in the second column

            find_latindex = lat
            find_lonindex = lon

            sfcWind_tem = ds['sfcWind'].values
            lon_vals = ds['lon'].values
            lat_vals = ds['lat'].values

            lat_index = np.abs(lat_vals - find_latindex).argmin()
            lon_index = np.abs(lon_vals - find_lonindex).argmin()

            sfcWind_select = sfcWind_tem[:, lat_index, lon_index]
            time = ds['time'].values
            df = pd.DataFrame({'time': time, str(lon) + '_' + str(lat): sfcWind_select})
            dic[str(lon) + '_' + str(lat)] = sfcWind_select
            i += 1
            print(str(row) + ' ok')
            csv_counter += 1  # 增加CSV文件计数器

    # 创建一个默认字典
    new_dict = defaultdict(list)
    j = 0
    # 将具有相同值的键组合到一起
    for key, values in dic.items():
        new_dict[tuple(values)].append(key)
        print(j)
        j += 1

    # 构建新的字典
    result_dict = {}
    # 求相同风速的平均
    for values, keys in new_dict.items():
        total_lon = 0
        total_lat = 0
        for item in keys:
            value_lon = float(item.split("_")[0])
            value_lat = float(item.split("_")[-1])
            total_lon += value_lon
            total_lat += value_lat

        average_lon = total_lon / len(keys)
        average_lat = total_lat / len(keys)

        result_dict[f"{str(average_lon)}_{str(average_lat)}"] = len(keys)
        print(average_lon, average_lon)

    # 输出新的字典
    print(result_dict)
# 将字典转换为DataFrame
df = pd.DataFrame(result_dict.items(), columns=['lon_lat', 'area'])

# 保存DataFrame到CSV文件
df.to_csv(r"D:\sfcWind\all2.csv", index=False)

print("数据已成功写入CSV文件")